import json
import pandas as pd
import sys
import os
from datetime import datetime
from pathlib import Path

class Config():
    data = {}

    def __init__(self):
        self.data = self.loads()

    # 读取
    def loads(self):
        with open(Config.resource_path('./data/data.json'), 'r', encoding='utf-8') as f:
            data = json.load(f)  # 返回Python字典/列表
        return data    

    # 写入数据
    def dump(self):
        with open(Config.resource_path('./data/data.json'),'w',encoding="utf-8") as f:
            json.dump(self.data,f,ensure_ascii=False,indent=4)

    def resource_path(relative_path):
        """ 获取资源绝对路径,兼容开发环境和PyInstaller打包后环境 """
        if getattr(sys, 'frozen', False):  # 判断是否处于打包环境
            base_path = sys._MEIPASS  # 临时资源目录（PyInstaller解压路径）
        else:
            base_path = os.path.abspath(".")  # 开发环境的当前目录
        return Path(os.path.join(base_path, relative_path))        
    
    # excel转json
    def toExcel(path,type='userlist'):
        df = pd.read_excel(path)
        json_data = df.to_json(orient='records', force_ascii=False)
        dist_data = json.loads(json_data)

        if type == "userlist":
            keylist = {"工号":"number","科室/岗位":"position","姓名":"name","中奖几率":"winRate","奖项":"winPro"}
            savePath = Config.resource_path('./data/userlist.json')
        else:
            keylist = {"奖项":"winPro","奖品名称":"winTitle","数量":"number"}
            savePath = Config.resource_path('./data/awardlist.json')
        data = []
        for val in dist_data:
            data.append({keylist.get(k, k): v for k, v in val.items()})    

        with open(savePath,'w',encoding="utf-8") as f:
            json.dump(data,f,ensure_ascii=False,indent=4)

        return True    
    
    # 写入winList数据
    def wWinList(data):
        with open(Config.resource_path('./data/winlist.json'),'w',encoding="utf-8") as f:
            json.dump(data,f,ensure_ascii=False,indent=4)
        pass    

    # 读取json信息
    def toJson(path):
        with open(Config.resource_path(path), 'r', encoding='utf-8') as f:
            if os.path.getsize(Config.resource_path(path)) == 0:
                return False
            else:
                data = json.load(f)  # 返回Python字典/列表
                return data
            
    # 导出中奖名单
    def exportWinList():
        winlist = Config.toJson(Config.resource_path('./data/winlist.json'))    
        keylist = {"number":"工号","position":"科室/岗位","name":"姓名","winPro":"奖项","winTitle":"奖品名称"}
        data = []
        # 替换键名
        for val in winlist:
            del val['winRate']
            data.append({keylist.get(k, k): v for k, v in val.items()}) 
        df = pd.DataFrame(data)
        now = datetime.now()
        formatted_time = now.strftime("%Y_%m_%d_%H_%M_%S")
        df.to_excel(f"{formatted_time}.xlsx", index=False)

